<!-- 文化内容管理页面 -->
<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import WangEditor from "@/components/WangEditor/index.vue"
import { getContentPage, getContentForm, addContent, updateContent, deleteContent } from '@/api/culture/content'
import { getCategoryPage } from '@/api/culture/category'

// 搜索参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: '',
  categoryId: ''
})

// 文章内容
const content = ref('')

// 表单数据
const formData = reactive({
  id: '',
  title: '',
  categoryId: '',
  author: '',
  status: 1
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)

// 表格列配置
const columns = [
  { prop: 'id', label: 'ID', width: '80' },
  { prop: 'title', label: '标题', minWidth: '180' },
  { prop: 'categoryName', label: '分类', width: '120' },
  { prop: 'author', label: '作者', width: '120' },
  { prop: 'createTime', label: '发布日期', width: '180' },
  { prop: 'status', label: '状态', width: '100' }
]

// 分类选项
const categoryOptions = ref([])

// 状态选项
const statusOptions = ref([
  { label: '已发布', value: 1 },
  { label: '草稿', value: 0 }
])

// 对话框显示控制
const dialogVisible = ref(false)
const dialogTitle = ref('新增文章')
const formRef = ref(null)

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ]
}

// 获取分类列表
const getCategoryOptions = () => {
  console.log('开始获取分类列表')
  getCategoryPage({pageNum: 1, pageSize: 100, status: 1}).then(res => {
      console.log("分类数据返回:", res);
      categoryOptions.value = (res.list || []).map((item) => ({
      label: item.name,
      value: item.id
    }))
    console.log('处理后的分类选项:', categoryOptions.value)
  }).catch(error => {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  })
}

// 获取文章列表
const getArticleList = () => {
  loading.value = true
  getContentPage(queryParams).then(res => {
    console.log('文章列表数据:', res)
    // 确保列表数据中有分类名称
    const list = (res.list || []).map(item => {
      // 如果没有categoryName但有categoryId，尝试从分类选项中获取名称
      if (!item.categoryName && item.categoryId) {
        const category = categoryOptions.value.find(opt => opt.value === item.categoryId)
        if (category) {
          item.categoryName = category.label
        }
      }
      return item
    })
    tableData.value = list
    total.value = res.total || 0
    loading.value = false
  }).catch(error => {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败')
    loading.value = false
  })
}

// 处理分页变化
const handlePageChange = (page) => {
  queryParams.pageNum = page
  getArticleList()
}

// 处理每页数量变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  queryParams.pageNum = 1
  getArticleList()
}

// 打开新增对话框
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '新增文章'
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑文章'
  resetForm()
  
  // 获取详细表单数据
  loading.value = true
  getContentForm(row.id).then(res => {
    Object.assign(formData, res)
    // 设置富文本内容
    content.value = res.content || ''
    loading.value = false
    dialogVisible.value = true
  }).catch(() => {
    loading.value = false
  })
}

// 删除文章
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该文章吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteContent(row.id).then(() => {
      ElMessage.success('删除成功')
      getArticleList()
    }).catch(error => {
      ElMessage.error(error.message || '删除失败')
    })
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  if (!formRef.value) return
  
  formRef.value.validate((valid) => {
    if (valid) {
      if (!content.value) {
        ElMessage.warning('请输入文章内容')
        return
      }
      
      // 构建提交数据
      const isUpdate = formData.id !== ''
      const submitData = {
        ...(isUpdate ? formData : { title: formData.title, categoryId: formData.categoryId, author: formData.author, status: formData.status }),
        content: content.value
      }
      
      const apiMethod = isUpdate ? updateContent(formData.id, submitData) : addContent(submitData)
      
      apiMethod.then(() => {
        ElMessage.success(isUpdate ? '更新成功' : '添加成功')
        dialogVisible.value = false
        getArticleList()
      }).catch(error => {
        ElMessage.error(error.message || (isUpdate ? '更新失败' : '添加失败'))
      })
    }
  })
}

// 重置表单
const resetForm = () => {
  formData.id = ''
  formData.title = ''
  formData.categoryId = ''
  formData.author = ''
  formData.status = 1
  content.value = ''
  
  // 延迟重置校验结果
  if (formRef.value) {
    nextTick(() => {
      formRef.value.resetFields()
    })
  }
}

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  getArticleList()
}

// 重置搜索
const resetSearch = () => {
  queryParams.title = ''
  queryParams.categoryId = ''
  handleSearch()
}

// 页面加载时获取数据
onMounted(() => {
  // 先获取分类，再获取文章列表
  getCategoryOptions()
  // 等待分类数据加载完成后再获取文章列表
  setTimeout(() => {
    getArticleList()
  }, 500)
})
</script>

<template>
  <div class="app-container">
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">新增文章</el-button>
      <el-input
        v-model="queryParams.title"
        placeholder="搜索文章标题"
        class="search-input"
        clearable
        @keyup.enter="handleSearch"
      />
      <el-select v-model="queryParams.categoryId" placeholder="文章分类" clearable style="width: 180px;">
        <el-option
          v-for="item in categoryOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="success" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 文章列表 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
    >
      <el-table-column
        v-for="column in columns"
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        :width="column.width"
        :min-width="column.minWidth"
      >
        <template #default="{ row }" v-if="column.prop === 'status'">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '已发布' : '草稿' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" width="150">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 文章编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="80%"
      destroy-on-close
      :top="'5vh'"
      :center="true"
    >
      <el-form :model="formData" :rules="rules" label-width="100px" ref="formRef">
        <el-form-item label="文章标题" prop="title" required>
          <el-input v-model="formData.title" placeholder="请输入文章标题" />
        </el-form-item>
        
        <el-form-item label="文章分类" prop="categoryId" required>
          <el-select v-model="formData.categoryId" placeholder="请选择文章分类" style="width: 100%">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="作者">
          <el-input v-model="formData.author" placeholder="请输入作者" />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">发布</el-radio>
            <el-radio :label="0">草稿</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="文章内容" required>
          <div class="editor-container">
            <WangEditor v-model="content" height="400px" />
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.app-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-input {
  width: 240px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 修复弹窗和输入框宽度问题 */
:deep(.el-form-item__content) {
  width: 100%;
}

.editor-container {
  width: 100%;
}

:deep(.el-dialog) {
  display: flex;
  flex-direction: column;
}

:deep(.el-dialog__body) {
  padding: 20px 30px;
  flex: 1;
  overflow-y: auto;
  max-height: calc(85vh - 120px); /* 减去标题和底部按钮高度 */
}
</style>
